<template>
  <div class="category-edit-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-2xl font-bold text-gray-900 ">编辑分类</h1>
        </div>
        <div class="flex space-x-3">
          <el-button type="success" @click="handleSave" :loading="saving" class="w-[90px]">
            保存
          </el-button>
          <el-button type="danger" @click="handleDelete" class="w-[90px]">
            删除
          </el-button>
          <el-button type="default" @click="handleCancel" class="w-[90px]">
            取消
          </el-button>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>

    <!-- 使用共享的分类表单组件 -->
    <div v-else class="form-container">
      <CategoryForm
        ref="categoryFormRef"
        mode="edit"
        :category-id="categoryId"
        :initial-data="categoryData"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import CategoryForm from '~/components/admin/CategoryForm.vue'
import { categoryAPI } from '~/services/api'

// 定义页面布局
definePageMeta({
  layout: 'admin'
})

const router = useRouter()
const route = useRoute()
const categoryFormRef = ref()
const loading = ref(true)
const saving = ref(false)

// 获取分类ID
const categoryId = computed(() => route.params.id)

// 分类数据
const categoryData = ref({})

// 加载分类详情
const loadCategoryDetail = async () => {
  try {
    loading.value = true
    
    // 调用后端API获取分类详情（该API直接返回对象数据）
    const category = await categoryAPI.getCategoryById(categoryId.value)
    
    // 设置分类数据
    categoryData.value = {
      id: category.id,
      name: category.name,
      code: category.code,
      sortOrder: category.sortOrder,
      status: category.status,
      description: category.description,
      parentId: category.parentId,
      level: category.level,
      path: category.path,
      createdAt: category.createdAt,
      updatedAt: category.updatedAt
    }
    
  } catch (error) {
    console.error('加载分类详情失败:', error)
    ElMessage.error('加载分类详情失败')
  } finally {
    loading.value = false
  }
}

// 保存分类
const handleSave = async () => {
  try {
    saving.value = true
    
    // 验证表单
    const valid = await categoryFormRef.value?.validate()
    if (!valid) return
    
    // 获取表单数据
    const formData = categoryFormRef.value?.getFormData()
    
    // 调用后端API更新分类
    await categoryAPI.updateCategory(categoryId.value, formData)
    
    ElMessage.success('分类修改成功')
    router.push('/admin/category/list')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error(error.message || '保存失败，请重试')
  } finally {
    saving.value = false
  }
}

// 删除分类
const handleDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除「${categoryData.value.name}」分类吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    // 调用后端API删除分类
    await categoryAPI.deleteCategory(categoryId.value)
    
    ElMessage.success('分类删除成功')
    router.push('/admin/category/list')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error(error.message || '删除失败，请重试')
    }
  }
}

// 取消操作
const handleCancel = async () => {
  // 检查是否有未保存的修改
  try {
    await ElMessageBox.confirm(
      '确定要离开吗？未保存的修改将会丢失。',
      '确认离开',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    router.push('/admin/category/list')
  } catch {
    // 用户取消离开
  }
}

// 页面初始化
onMounted(async () => {
  await loadCategoryDetail()
})
</script>

<style scoped>
.category-edit-page {
  @apply min-h-screen bg-gray-50 ;
}

.page-header {
  @apply bg-white  shadow-sm border-b border-gray-200  px-6 py-4 mb-6;
}

.loading-container {
  @apply px-6 pb-6;
}

.form-container {
  @apply px-6 pb-6;
}
</style>
